package com.deng.test.handler;

import com.deng.test.annotation.CertificateSkip;
import com.deng.test.exception.InvalidTokenException;
import com.deng.test.util.JwtUtil;
import io.jsonwebtoken.Claims;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.Optional;

/**
 * @auther deng
 * @date 2024/5/27 下午3:43
 * @desc: jwt认证类
 */
@Component
public class JWTRequestHandler implements HandlerInterceptor {
    private final JwtUtil jwtUtil;

    public JWTRequestHandler(JwtUtil jwtUtil) {
        this.jwtUtil = jwtUtil;
    }

    private final Logger logger = LoggerFactory.getLogger(JWTRequestHandler.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //如果使用@CertificateSkip可以跳过认证
        logger.info("handler:{}", handler.getClass());
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            if (method.isAnnotationPresent(CertificateSkip.class)) {
                return true;
            }
        }
        //认证Token是否合法
        String authentication = request.getHeader("authentication");
        Optional.ofNullable(authentication).orElseThrow(() -> new InvalidTokenException("token is empty"));
        Claims claims = jwtUtil.checkoutJwt(authentication);
        logger.info("authentication:{},claims:{}", authentication, claims);
        request.setAttribute("claims", claims);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
